package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.McInfoListMapper;
import cc.rengu.igas.momp.common.dao.McMchntInfoMapper;
import cc.rengu.igas.momp.common.dao.MchntInfoMapper;
import cc.rengu.igas.momp.common.dao.impl.McInfoListMapperImpl;
import cc.rengu.igas.momp.common.dao.impl.McMchntInfoMapperImpl;
import cc.rengu.igas.momp.common.dao.impl.MchntInfoMapperImpl;
import cc.rengu.igas.momp.common.entity.CcbMcDetailListInObj;
import cc.rengu.igas.momp.common.entity.CcbMcDetailListOutObj;
import cc.rengu.igas.momp.common.entity.TBMchntBaseInfo;
import cc.rengu.igas.momp.common.entity.TMMcMchntInfo;
import cc.rengu.igas.momp.common.enums.QueryTypeEnum;
import cc.rengu.igas.momp.common.enums.RespCodeEnum;
import cc.rengu.igas.momp.common.util.CommonMessageCheck;
import cc.rengu.igas.momp.facade.bean.CashierMcCashbackDetailBean;
import cc.rengu.igas.momp.facade.request.CashierMcCashbackDetailRequest;
import cc.rengu.igas.momp.facade.response.CashierMcCashbackDetailResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收银员返现明细查询接口实现()
 * 收银员查询使用
 *
 * @author Jinan Liu
 * @version 1.0.0
 * @date 2020/6/14 16:55
 */

public class QueryCashierCashbackDetailService extends RadpService {
    private String globalInstId;
    private String globalQueryType;
    private String globalQueryRole;
    private String globalQueryOrgId;

    @Override
    protected int bizInit(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizProcess(String s, int i) {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        try {

            CashierMcCashbackDetailRequest cashierMcCashbackDetailRequest = new CashierMcCashbackDetailRequest();
            ConvertUtil.convertOutput(cashierMcCashbackDetailRequest);

            CashierMcCashbackDetailResponse cashierMcCashbackDetailResponse = new CashierMcCashbackDetailResponse();
            cashierMcCashbackDetailResponse.setHeader(cashierMcCashbackDetailRequest.getHeader());
            BizResponse<CashierMcCashbackDetailResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(cashierMcCashbackDetailResponse);

            globalInstId = cashierMcCashbackDetailRequest.getHeader().getInstId();
            String timeStamp = new SimpleDateFormat(CommonConstant.TIMESTAMP_FORMAT).format(new Date());
            String oprId = cashierMcCashbackDetailRequest.getQueryId();
            globalQueryOrgId = cashierMcCashbackDetailRequest.getQueryOrgId();

            rglog.info("机构<{}>在<{}>由<{}>开始查询收银员返现明细列表信息流程", globalInstId, timeStamp, oprId);

            globalQueryType = cashierMcCashbackDetailRequest.getQueryType();
            globalQueryRole = cashierMcCashbackDetailRequest.getQueryRole();

            /* 报文检查 */
            CommonMessageCheck.checkBizMessageHeader(globalQueryType, oprId, globalQueryRole, rglog);

            /* 检查操作员所属机构号 */
            if (StringUtil.isNullorEmpty(globalQueryOrgId)) {
                rglog.error("法人机构号<{}>的操作员<{}>的所属机构为空!", globalInstId, oprId);
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }

            // 服务调用
            BizResponse<CashierMcCashbackDetailResponse> bizResponseNew = queryCashierCashbackDetail(xmlTreeUtil, cashierMcCashbackDetailRequest, cashierMcCashbackDetailResponse);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    /**
     * @param cashierMcCashbackDetailRequest
     * @param cashierMcCashbackDetailResponse
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/3/17 00:28
     * @description 查询收银员返现类营销活动明细列表信息
     * @return: void
     */
    private BizResponse<CashierMcCashbackDetailResponse> queryCashierCashbackDetail(XmlTreeUtil xmlTreeUtil, CashierMcCashbackDetailRequest cashierMcCashbackDetailRequest, CashierMcCashbackDetailResponse cashierMcCashbackDetailResponse) throws Exception {

        String traceNo = cashierMcCashbackDetailRequest.getHeader().getTraceNo();
        BizResponse<CashierMcCashbackDetailResponse> bizResponse = new BizResponse<>();
        List<CashierMcCashbackDetailBean> cashierMcCashbackDetailBeans;

        List<CcbMcDetailListOutObj> ccbMcDetailListOutObjList = new ArrayList<>();
        PageResult pageResult = null;

        /* 数据库入参赋值 */
        CcbMcDetailListInObj ccbMcDetailListInObj = setupDatabaseInputObject(cashierMcCashbackDetailRequest);

        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(Integer.parseInt(cashierMcCashbackDetailRequest.getPageIndex()));
        pageInfo.setPageSize(Integer.parseInt(cashierMcCashbackDetailRequest.getPageSize()));

        /* 根据角色权限查询数据 */
        if (globalQueryType.equals(QueryTypeEnum.CASHIER_QYERY_TYPE.getQueryTypeCode())) {
            //收银员Id
            String userId = cashierMcCashbackDetailRequest.getQueryId();
            ccbMcDetailListInObj.setId(userId);
            rglog.info("流水号:<{}>,查询收银员返现营销活动返现明细开始...!", traceNo);
            pageResult = selectCashierCashbackDetailByUserId(ccbMcDetailListInObj, pageInfo);

        } else {
            /* 其他查询角色不支持 */
            rglog.error("流水号:<{}>,当前<{}>角色的查询用户<{}>无权限操作数据!", traceNo, globalQueryRole, globalQueryType);
            throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_OPER_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_OPER_ERROR.getRespDesc());
        }
        /* 根据取出记录条数做对应处理 */
        if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult() || pageResult.getResult().isEmpty()) {
            rglog.info("流水号:<{}>,根据查询条件查询到0条收银员返现活动明细信息!", traceNo);
            cashierMcCashbackDetailResponse.setTotalPage(CommonConstant.ZERO_COMMON_CONSTANT);
            cashierMcCashbackDetailResponse.setTotalRows(CommonConstant.ZERO_COMMON_CONSTANT);
        } else {
            rglog.info("流水号:<{}>,根据查询条件查询到<{}>条收银员返现活动明细信息!", traceNo, pageResult.getResult().size());
            for (Object object : pageResult.getResult()) {
                ccbMcDetailListOutObjList.add((CcbMcDetailListOutObj) object);
            }

            cashierMcCashbackDetailBeans = ccbMcDetailListOutObjList.stream().map(this::convertMcMoneyOffInfo).collect(Collectors.toList());
            cashierMcCashbackDetailResponse.setCashbackDetailList(cashierMcCashbackDetailBeans);

            cashierMcCashbackDetailResponse.setTotalPage(Integer.toString(pageResult.getPageInfo().getTotalPage()));
            cashierMcCashbackDetailResponse.setTotalRows(Integer.toString(pageResult.getPageInfo().getTotalRows()));
        }
        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        cashierMcCashbackDetailResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        cashierMcCashbackDetailResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        cashierMcCashbackDetailResponse.setPageIndex(cashierMcCashbackDetailRequest.getPageIndex());
        cashierMcCashbackDetailResponse.setPageSize(cashierMcCashbackDetailRequest.getPageSize());

        bizResponse.setResult(cashierMcCashbackDetailResponse);

        return bizResponse;
    }

    /**
     * 数据库查询前赋值数据库实体类入参
     *
     * @param queryCashbackToCashierDetailRequest 收银员返现明细列表查询接口请求对象
     * @return cc.rengu.igas.momp.common.entity.CcbMcListInfoInObj 收银员返现明细列表查询使用实体类入参
     * @author Jinan Liu
     * @date 2020/5/28 12:57
     */
    private CcbMcDetailListInObj setupDatabaseInputObject(CashierMcCashbackDetailRequest queryCashbackToCashierDetailRequest) {

        CcbMcDetailListInObj ccbMcDetailListInObj = new CcbMcDetailListInObj();

        /* 机构编码 */
        ccbMcDetailListInObj.setInstId(globalInstId);
        rglog.info("INST_ID=<{}>", globalInstId);

        /* 营销活动编号 */
        if (!StringUtil.isNullorEmpty(queryCashbackToCashierDetailRequest.getMcNo())) {
            ccbMcDetailListInObj.setMcNo(queryCashbackToCashierDetailRequest.getMcNo());
        }
        /* 查询主体角色 */
        if (!StringUtil.isNullorEmpty(queryCashbackToCashierDetailRequest.getQueryRole())) {
            ccbMcDetailListInObj.setRole(queryCashbackToCashierDetailRequest.getQueryRole());
        }
        /* 查询主体所属机构 */
        if (!StringUtil.isNullorEmpty(queryCashbackToCashierDetailRequest.getQueryOrgId())) {
            ccbMcDetailListInObj.setOrgId(queryCashbackToCashierDetailRequest.getQueryOrgId());
        }
        /* 查询主体 */
        if (!StringUtil.isNullorEmpty(queryCashbackToCashierDetailRequest.getQueryId())) {
            ccbMcDetailListInObj.setId(queryCashbackToCashierDetailRequest.getQueryId());
        }
        return ccbMcDetailListInObj;
    }

    /**
     * 收银员查询数据
     *
     * @param ccbMcDetailListInObj 收银员返现活动明细列表查询使用实体类入参
     * @param pageInfo             数据库操作分页请求实体类
     * @return cc.rengu.oltp.utility.bean.PageResult 数据库操作分页应答实体类
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/28 13:13
     */
    private PageResult selectCashierCashbackDetailByUserId(CcbMcDetailListInObj ccbMcDetailListInObj, PageInfo pageInfo) throws Exception {

        McInfoListMapper mcInfoListMapper = new McInfoListMapperImpl();
        return mcInfoListMapper.selectCashierCashbackDetailByUserId(ccbMcDetailListInObj, pageInfo);

    }

    /**
     * 数据库实体类和接口实体类数据转换
     *
     * @param ccbMcDetailListOutObj 收银员活动返现明细列表查询使用实体类出参
     * @return cc.rengu.igas.momp.facade.bean.CashierCashbackMcListInfoBean 收银员活动返现明细列表查询接口应答对象
     * @author Jinan Liu
     * @date 2020/5/28 00:15
     */
    private CashierMcCashbackDetailBean convertMcMoneyOffInfo(CcbMcDetailListOutObj ccbMcDetailListOutObj) {

        CashierMcCashbackDetailBean cashierMcCashbackDetailBean = new CashierMcCashbackDetailBean();
        try {
            /* 营销活动编号 */
            cashierMcCashbackDetailBean.setMcNo(ccbMcDetailListOutObj.getMcNo());
            /* 营销活动名称 */
            cashierMcCashbackDetailBean.setMcName(ccbMcDetailListOutObj.getMcName());
            /* 收银员标识 */
            cashierMcCashbackDetailBean.setUserId(ccbMcDetailListOutObj.getUserId());
            /* 收银员所属商户号 */
            cashierMcCashbackDetailBean.setMchntNo(ccbMcDetailListOutObj.getUserInst());
            /* 收银员卡号 */
            cashierMcCashbackDetailBean.setAcctNo(ccbMcDetailListOutObj.getAcctNo());
            /* 收银员户名 */
            cashierMcCashbackDetailBean.setAcctName(ccbMcDetailListOutObj.getAcctName());
            /* 打款状态 */
            cashierMcCashbackDetailBean.setCashbackStatus(ccbMcDetailListOutObj.getCashbackStatus());
            /* 打款类型 */
            cashierMcCashbackDetailBean.setCashbackMethod(ccbMcDetailListOutObj.getCashbackMethod());
            /* 打款金额 */
            if (StringUtil.isNullorEmpty(ccbMcDetailListOutObj.getCashbackAmt())) {
                cashierMcCashbackDetailBean.setCashbackAmt("0.00");
            } else {
                cashierMcCashbackDetailBean.setCashbackAmt(ccbMcDetailListOutObj.getCashbackAmt());
            }
            /* 打款时间 */
            cashierMcCashbackDetailBean.setCashbackTime(ccbMcDetailListOutObj.getCashbackTime());
            /* 统计周期起始日期 */
            cashierMcCashbackDetailBean.setStatStartDate(ccbMcDetailListOutObj.getStatStartDate());
            /* 统计周期结束日期 */
            cashierMcCashbackDetailBean.setStatEndDate(ccbMcDetailListOutObj.getStatEndDate());

        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("转换营销活动信息异常,异常信息:<{}>", byteArrayOutputStream.toString());
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        return cashierMcCashbackDetailBean;
    }
}
